const $common = require('../../common/common-req.js');
const requestHandler = require('../../common/request-handler.js');
var router = $common.express.Router();

// 添加评论
router.post('/', async (req, res) => {
    const commentId = $common.strLen();
    const createTime = new Date();
    let param = ['articleId', 'phone', 'content', 'replyId'];
    let vital = ['articleId', 'phone', 'content'];
    let expand = {commentId, createTime};
    let insertSql = 'insert into articlecomments(id, articleId, phone, content, replyId, createTime) values(?, ?, ?, ?, ?, ?)';
    let insertArr = ['commentId', 'articleId', 'phone', 'content', 'replyId', 'createTime'];
    let moduleName = '评论';
    let isExitArr = [];
    let exitTableName = '';
    requestHandler.postHandler(req, res, param, vital, expand, insertSql, insertArr, moduleName, isExitArr, exitTableName);
})

// 获取文章评论,还差子节点
router.get('/', (req, res) => {
    let param = ['pageNum', 'pageSize', 'articleId'];
    param = $common.getQueryParam(req, 'query', param);
    let { pageNum, pageSize, articleId } = param;
    pageNum = pageNum > 1 ? pageNum - 1 : 0;
    pageSize = +pageSize;
    let vital = ['pageNum', 'pageSize', 'articleId'];
    if (!$common.vitalParam(param, vital)) {
        res.send($common.setErrorData('缺少必须参数'));
    } else {
        let sql = 'select * from commentview where articleId=? and replyId IS NULL order by createTime desc limit ?, ?';
        let arr = [articleId, pageNum, pageSize];
        $common.db_mysql.select(sql, arr, async result => {
            let selectAttr = ['id', 'articleId', 'phone', 'content', 'userName', 'userSrc', 'replyId', 'createTime'];
            let resArr = $common.selectHandle(result, selectAttr);
            if (resArr.length > 0) {
                const replys = await getReply(articleId);
                console.log('replys', replys)
                $common.resData.data.total = resArr.length;
                resArr = handlerComment(resArr, replys)
                $common.resData.data.list = resArr;
                $common.resData.msg = '获取文章评论成功';
                res.send($common.resData);
            } else {
                $common.resData.data.list = [];
                $common.resData.data.total = 0;
                $common.resData.msg = '获取文章评论成功';
                res.send($common.resData);
            }
        })
    }
})

// 将评论处理层父子层级
function handlerComment(list, replys) {
    let temp = {}
    list.map(item => {
        item.children = []
        temp[item.id] = item
    })
    console.log('temp', temp)
    replys.map(item => {
        console.log('item.replyId', item.replyId)
        temp[item.replyId].children.push(item)
    })
    let result = []
    for (let k in temp) {
        result.push(temp[k])
    }
    return result
}
// 添加回复
router.post('/reply', async (req, res) => {
    const replyId = $common.strLen();
    const createTime = new Date();
    let param = ['commentId', 'phone', 'content'];
    let vital = ['commentId', 'phone', 'content'];
    let expand = {replyId, createTime};
    let insertSql = 'insert into articlereply(id, phone, content, commentId, createTime) values(?, ?, ?, ?, ?)';
    let insertArr = ['replyId', 'phone', 'content', 'commentId', 'createTime'];
    let moduleName = '回复';
    let isExitArr = [];
    let exitTableName = '';
    requestHandler.postHandler(req, res, param, vital, expand, insertSql, insertArr, moduleName, isExitArr, exitTableName);
})

// 获取回复
async function getReply(articleId) {
    let sql = 'select * from commentreplyview where articleId=? order by createTime asc';
    let arr = [articleId];
    let result = await $common.db_mysql.asyncSelect(sql, arr);
    let selectAttr = ['id', 'phone', 'content', 'userName', 'createTime', 'bePhone', 'articleId', 'articleTitle', 'beUserSrc', 'beUserName', 'beContent', 'replyId'];
    let reNameArr = ['id', 'phone', 'content', 'userName', 'createTime', 'bePhone', 'articleId', 'articleTitle', 'beUserSrc', 'beUserName', 'beContent', 'replyId'];
    let resArr = $common.selectHandle(result, selectAttr, reNameArr);
    return resArr
}

/**
 * 根据用户获取相关的评论
 * */
router.get('/getUserComment', (req, res) => {
    let param = ['pageNum', 'pageSize', 'userId'];
    let vital = ['pageNum', 'pageSize', 'userId'];
    let totalSql = 'select count(*) as count from commentreplyview where bePhone = ?';
    let expand = ['userId'];
    let getSql = 'select * from commentreplyview where bePhone = ? order by createTime limit ?, ?';
    let getArr = ['userId'];
    let selectAttr = ['id', 'phone', 'content', 'userName', 'createTime', 'bePhone', 'articleId', 'articleTitle'];
    let reName = ['id', 'phone', 'content', 'userName', 'createTime', 'bePhone', 'articleId', 'articleTitle'];
    let moduleName = '用户相关评论';
    let checkBlob = false;
    let blobArr = [];
    requestHandler.getHandler(req, res, param, vital, totalSql, expand, getSql, getArr, selectAttr, reName, moduleName, checkBlob, blobArr, (list) => {
        console.log(list)
        list.map(item => {
            let sql = 'update articlecomments set isRead=1 where id=?';
            let arr = [item.id];
            $common.db_mysql.update(sql, arr, result => {
                if (result) {
                    console.log('修改成功')
                } else {
                    console.log('修改失败')
                }
            })
        })
        
    });
})


module.exports = router;